package org.rsbot.util;

import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import org.rsbot.bot.Bot;

public class ColorUtil {

    public static Color grabColorAt(int x, int y) {
        try {
            return new Color(Bot.getBotBuffer().getRGB(x, y));
        } catch (Exception ignored) {
            return null;
        }
    }

    public static Point[] findColorInArea(Rectangle q, Color desired, Color tolerance) {
        ArrayList<Point> al = new ArrayList<Point>();
        int rt = tolerance.getRed(), gt = tolerance.getGreen(), bt = tolerance.getBlue();
        for (int i = q.x; i < q.x + q.width; i++) {
            for (int j = q.y; j < q.y + q.height; j++) {
                Color c = grabColorAt(i, j);
                if (c == null) {
                    continue;
                }
                int r = Math.abs(c.getRed() - desired.getRed());
                int g = Math.abs(c.getGreen() - desired.getGreen());
                int b = Math.abs(c.getBlue() - desired.getBlue());
                if (r <= rt && b <= bt && g <= gt) {
                    al.add(new Point(i, j));
                }
            }
        }
        al.trimToSize();
        if (al.isEmpty()) {
            return null;
        }
        return al.toArray(new Point[al.size()]);
    }
}
